import { httpError, Inject, Middleware } from '@midwayjs/core';
import { Context, NextFunction } from '@midwayjs/koa';
import { JwtService } from '@midwayjs/jwt';


@Middleware()
export class JwtMiddleware {
  @Inject()
  jwtService: JwtService;


  public static getName(): string {
    return 'jwt';
  }

  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      // 认证身份信息判断和获取
      if (!ctx.headers['authorization']) {
        throw new httpError.UnauthorizedError();
      }

      const parts = ctx.get('authorization').trim().split(' ');

      if (parts.length !== 2) {
        throw new httpError.UnauthorizedError();
      }

      const [scheme, token] = parts;

      if (/^Bearer$/i.test(scheme)) {
        // jwt.verify 方法验证 token 是否合法
        const userInfo = this.jwtService.verifySync(token, {
          complete: true,
        });
        if (typeof userInfo !== 'string') {
          ctx.user = userInfo.payload;
          ctx.user.role = ctx.user.status.name;
        }
        await next();
      }
    };
  }

  // 配置忽略认证校验的路由地址
  public ignore(ctx: Context): boolean {
    return ['/user/register', '/user/login'].includes(ctx.path);
  }
}
